package com.gemme.gemme.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.gemme.gemme.R;
import com.gemme.gemme.gwc.OnProductBean;
import com.gemme.gemme.gwc.PaySucessActivity;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.manager.DataPares;
import com.gemme.gemme.util.StrUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PayDialog {

    boolean isPerson = true;
    boolean isDetail = true;
    private Context mContext;
    private String orderCode;
    private double orderSubtotal;
    private String refundReason;
    private String orderDetailId;
    private OnChangeLIstener onChangeLIstener;
    private OnProductBean onProductBean;

    public void showDialog(Context mContext){
        this.mContext = mContext;
        BottomDialog dialog = new BottomDialog(mContext, R.layout.pay_dialog,
                new int[]{R.id.close,R.id.tv_pay,R.id.ll_weixinpay,R.id.ll_alipay});

//        initView(dialog.getView());
        dialog.show();
        dialog.setOnBottomItemClickListener(new BottomDialog.OnBottomItemClickListener() {
            @Override
            public void onBottomItemClick(BottomDialog dialog, View view) {
                switch (view.getId()) {
                    case R.id.close:
                        dialog.dismiss();
                        break;

                    case R.id.tv_pay:
                        dialog.dismiss();
                        mContext.startActivity(new Intent(mContext, PaySucessActivity.class));
                        break;

                    case R.id.ll_weixinpay:
                        weixinpayMyServer();
                        break;

                    case R.id.ll_alipay:
                        alipayMyServer();
                        break;

                }
            }
        });
    }

    private void alipayMyServer() {
/*        String url = "http://192.168.1.7:9999/ali/alipay/createOrder?" +
                "orderCode=" + "12346668912345678912345678966666" +
                "&orderSubtotal=" + "0.01" ;  */



        if(TextUtils.isEmpty(orderCode) || orderSubtotal < 0){
            Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT).show();
        }
        String url =  DataManager.BaseUrl + "ali/alipay/createOrder?" +
                "orderCode=" + orderCode +
                "&orderSubtotal=" + orderSubtotal +
                "&falg=" + 1 ;//订单支付类型
        if(!TextUtils.isEmpty(orderDetailId)){
            url = url + "&orderDetailId=" + orderDetailId;
        }


        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
        DataManager.toServer3(mContext, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    if(DataPares.isSucess(mContext,response)){
                        AliPayBean aliPayBean = JSON.parseObject(response, AliPayBean.class);
                        System.out.println("");
                        alipay(aliPayBean.getData());
                        Object msg = aliPayBean.getMsg();
                        Toast.makeText(mContext, StrUtil.noNUll(msg), Toast.LENGTH_SHORT).show();
                    }



                }catch (Exception e){

                }
            }
        });
    }

    private void alipay(String orderInfo){
        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
              try {
                  PayTask alipay = new PayTask((Activity) mContext);
                  Map<String, String> result = alipay.payV2(orderInfo, true);
                  Log.i("msp", result.toString());


                  String code = (new JSONObject(result.get("result"))).getJSONObject("alipay_trade_app_pay_response").getString("code");
                  String total_amount = (new JSONObject(result.get("result"))).getJSONObject("alipay_trade_app_pay_response").getString("total_amount");

                  if("10000".equals(code)){
                        if (onChangeLIstener != null)
                            onChangeLIstener.onChangeLIstener();
                       if(onProductBean != null){
                           Intent intent = new Intent(mContext, PaySucessActivity.class);

                           intent.putExtra("data",JSON.toJSONString(onProductBean));
                           mContext.startActivity(intent);
                       }

                  }

              }catch (Exception e){

              }


            }
        };

// 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
        closeActivity();
    }

    private void weixinpayMyServer() {
/*
        String url = "http://192.168.1.7:9999/wechat/wechatPlat/unifiedOrderPay?" +
                "orderCode=" + "12345678912345678012345678912345" +
                "&orderSubtotal=" + "0.01" ;
*/

        if(TextUtils.isEmpty(orderCode) || orderSubtotal < 0){
            Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT).show();
        }


        String url = DataManager.BaseUrl + "wechat/wechatPlat/unifiedOrderPay?" +
                "orderCode=" + orderCode +
                "&orderSubtotal=" + orderSubtotal
                + "&falg=" + 1 ;//订单支付类型

        if(!TextUtils.isEmpty(orderDetailId)){
            url = url + "&orderDetailId=" + orderDetailId;
        }
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
        DataManager.toServer3(mContext, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    WeiXinPayBean weiXinPayBean = JSON.parseObject(response, WeiXinPayBean.class);
                    System.out.println("");

                  /*  new Thread(new Runnable() {
                        @Override
                        public void run() {

                        }
                    }).start();*/

                    weixinpay(weiXinPayBean);

                }catch (Exception e){

                }
            }
        });
    }

    private void closeActivity() {
        try {

            Handler mainHandler = new Handler(Looper.getMainLooper());
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    //已在主线程中，可以更新UI
                    Activity act = (Activity) mContext;
                    act.finish();
                }
            });


        }catch (Exception e){

        }
    }

    private void weixinpay(WeiXinPayBean weiXinPayBean) {
        try {
            String jsonString = null;
            if(onProductBean != null){
                onProductBean.setType(Constant.type_order_pay);
                jsonString = JSON.toJSONString(onProductBean);

            }

            IWXAPI api = WXAPIFactory.createWXAPI(mContext, weiXinPayBean.getData().getAppid());
            api.registerApp(weiXinPayBean.getData().getAppid());
            PayReq payRequest = new PayReq();
            payRequest.appId = weiXinPayBean.getData().getAppid();
            payRequest.partnerId =  weiXinPayBean.getData().getPartnerid();
            payRequest.prepayId =  weiXinPayBean.getData().getPrepayid();
//            payRequest.packageValue =  weiXinPayBean.getData().getPackageX();
            payRequest.packageValue =  "Sign=WXPay";
            payRequest.nonceStr =  weiXinPayBean.getData().getNoncestr();
            payRequest.timeStamp =  weiXinPayBean.getData().getTimestamp();
            payRequest.sign =  weiXinPayBean.getData().getSign();
            if (jsonString != null)
            payRequest.extData = jsonString;
            api.sendReq(payRequest);

            if(onChangeLIstener != null)
                onChangeLIstener.onChangeLIstener();

            System.out.println("");
//            closeActivity();
        }catch (Exception e){

        }
    }


    public void setData(String orderCode, double orderSubtotal,String refundReason, String orderDetailId) {

        this.orderCode = orderCode;
        this.orderSubtotal = orderSubtotal;
        this.refundReason = refundReason;
        this.orderDetailId = orderDetailId;
    }

    public void setOnChangeLIstener(OnChangeLIstener onChangeLIstener){
        this.onChangeLIstener = onChangeLIstener;
        System.out.println("");
    }

    public void setOnProductBean(OnProductBean onProductBean) {

        this.onProductBean = onProductBean;
    }
}
